var SceneVModel = function(options) {
	this.ctx = options.ctx;
	this.editor = options.editor;
	this.globe = options.editor.globe;
	this.isOpen=false;
	this.isOpenEdit=true;
	this.editPModel;
	this.dIndex;
	this.thingId;
	this.insTb;
	this.antennaTb;
	
}

SceneVModel.prototype.open = function(obj){
	var _this = this;
	var id=obj.id;
	_this.treeSelect;
	if(_this.isOpen){
		_this.createEditPModel(obj);
		_this.loadForm(obj);
		_this.thingId=obj.id;
		if( _this.insTb){
	        _this.insTb.reload({where:{
		    	thingId:_this.thingId
		    }}, 'data');
		}
/*        if(_this.antennaTb){
            _this.antennaTb.reload({where:{
    	    	thingId:_this.thingId
    	    }}, 'data');
        }*/
        
		return;
	}
	layer.load(2);
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/model/edit", {},"html", null);
	layer.closeAll('loading');
	if (!res) {
		layer.alert('系统异常！');
		return;
	}
	
	layer.open({
		id:'editModel',
	    type: 1,
	    anim:5,
	    title:'属性编辑',
	    area: '320px',
	    content:res,
	    shade:0,
	    offset: ['45px', '0px'],	
	    fixed:true,
	    move:false,
		skin:'layui-layer  layui-layer-adminRight layui-layer-city',
	    success: function (layero, dIndex) {
            $(layero).children('.layui-layer-content').css('overflow', 'hidden');
            $(layero).children('.layui-layer-content').css('height', 'calc(100% - 40px)');
            form.render();
            _this.dIndex=dIndex;
            _this.isOpen=true;
            _this.createEditPModel(obj);
            _this.loadForm(obj);
            _this.thingId=obj.id
            _this.renderProperty();
            //_this.renderAntenna();
		},
		end:function(){
			if(_this.editPModel){
				_this.editPModel.destroy();
				_this.editPModel=null;
			}
			_this.isOpen=false;
			_this.insTb=null;
			_this.antennaTb=null;
		}
	});	
}

SceneVModel.prototype.loadForm = function(obj){
	var _this = this;
	let data={};
	if(obj){
		data={
			id:obj.id,
			name:obj.name||'未命名',
			code:obj.code||'',
			sort:obj.attribute.sort,
			layerId:obj.parentId||'',
			
			x:obj.position.x||'',
			y:obj.position.y||'',
			z:obj.position.z||0,
			
			heading:obj.orientation.heading||0,
			pitch:obj.orientation.pitch||0,
			roll:obj.orientation.roll||0,
			
			type:obj.model.type||'',
			scale:obj.model.scale||1,
			minimumPixelSize:obj.model.minimumPixelSize||0,
			fill:obj.model.fill||0,
			fillColor:obj.model.fillColor||'',
			silhouette:obj.model.silhouette||0,
			silhouetteColor:obj.model.silhouetteColor||'',
			SceneVModelSilhouetteSize:obj.model.SceneVModelSilhouetteSize||0,
			distanceDisplayCondition:obj.model.distanceDisplayCondition||0,
			distanceNear:obj.model.distanceNear||0,
			distanceFar:obj.model.distanceFar||5000,
			animation:obj.model.animation||0,
			shadows:obj.model.shadows||false,
		}	
	}
	
	form.val('modelEditForm', data);
	let model=_this.globe.getById(data.id);
	$('#SceneVModelName').on('input', function() {
		 if(model){
			 model.updateAttribute({
				 name:$("#SceneVModelName").val(),
			 });
		 }
	 });
	$('#SceneVModelCode').on('input', function() {
		 if(model){
			 model.updateAttribute({
				 code:$("#SceneVModelCode").val()
			 });
		 }
	 });
	$('#SceneVModelSort').on('input', function() {
		 if(model){
			 model.updateAttribute({
				 sort:$("#SceneVModelSort").val()
			 });
		 }
	 });
	
	$('#SceneVModelScale').on('input', function() {
		 if(model){
			 model.updateScale($("#SceneVModelScale").val());
			 if(_this.editPModel){
				 _this.editPModel.update(model);
			 }
		 }
	 });
	
	$('#SceneVModelHeading').on('input', function() {
		 if(model){
			 model.updateHeading($("#SceneVModelHeading").val());
			 if(_this.editPModel){
				 _this.editPModel.update(model);
			 }
		 }
	 });
	
	$('#SceneVModelPitch').on('input', function() {
		 if(model){
			 model.updatePitch($("#SceneVModelPitch").val());
			 if(_this.editPModel){
				 _this.editPModel.update(model);
			 }
		 }
	 });	 
	 
	$('#SceneVModelRoll').on('input', function() {
		 if(model){
			 model.updateRoll($("#SceneVModelRoll").val());
			 if(_this.editPModel){
				 _this.editPModel.update(model);
			 }
		 }
	 });	
	
	$('#SceneVModelMinimumPixelSize').on('input', function() {
		 if(model){
			 model.updateMinimumPixelSize($("#SceneVModelMinimumPixelSize").val());
		 }
	});
	
	$('#modelZ').on('input', function() {
		 if(model){
			 model.updatePosition({
				 x:$("#modelX").val(),
				 y:$("#modelY").val(),
				 z:$("#modelZ").val(),
			 });
			 if(_this.editPModel){
				 _this.editPModel.update(model);
			 }
		 }
	 });
	
	colorpicker.render({//间隔颜色
		elem: '#fillColor',
		color: (data&&data.fillColor)?data.fillColor:null,
		format: 'rgb',
		predefine: true,
		alpha: true,
		done: function(color) {
			$('#fillColor-input').val(color); //向隐藏域赋值
			color || this.change(color); //清空时执行 change
			 if(model){
				 model.updateColor(color);
			 }
		},
		change: function(color) {
		}
	});
	
	colorpicker.render({//间隔颜色
		elem: '#silhouetteColor',
		color: (data&&data.silhouetteColor)?data.silhouetteColor:null,
		format: 'rgb',
		predefine: true,
		alpha: true,
		done: function(color) {
			$('#silhouetteColor-input').val(color); //向隐藏域赋值
			color || this.change(color); //清空时执行 change
			 if(model){
				 model.updateSilhouetteColor(color);
			 }
		},
		change: function(color) {}
	});
	
	$('#SceneVModelSilhouetteSize').on('input', function() {
		 if(model){
			 model.updateSilhouetteSize($("#SceneVModelSilhouetteSize").val());
		 }
	 });
	
	 $('#SceneVModelDistanceNear').on('input', function() {
		 if(model){
			 model.updateDistanceDisplay({
				 distanceNear:$("#SceneVModelDistanceNear").val(),
				 distanceFar:$("#SceneVModelDistanceFar").val(),
			 });
		 }
	 });
	 $('#SceneVModelDistanceFar').on('input', function() {
		 if(model){
			 model.updateDistanceDisplay({
				 distanceNear:$("#SceneVModelDistanceNear").val(),
				 distanceFar:$("#SceneVModelDistanceFar").val(),
			 });
		 }
	 });	
	
	$('#SceneVModelPositionBtn').click(function() {
		_this.globe.flyToPoisition(data);
	});
	
	$('#SceneVModelDeleteBtn').click(function() {
		layer.confirm('确定要删除模型吗？', {
			shade: .1
		}, function(index) {
			_this.delete(data);
		}, function(index) {
			layer.close(index);
			return false;
		});
	});
	
	form.on('select(fill)', function(data){
		if(data.value==1){
			$('#SceneVModel-fillColor-tr').show();
		}else {
			$('#SceneVModel-fillColor-tr').hide();
		}
		 if(model){
			 model.isFill(data.value);
		 }
	});
	
	form.on('select(silhouette)', function(data){
		if(data.value==1){
			$('#SceneVModel-silhouetteColor-tr').show();
			$('#SceneVModel-silhouetteSize-tr').show();
		}else {
			$('#SceneVModel-silhouetteColor-tr').hide();
			$('#SceneVModel-silhouetteSize-tr').hide();
		}
		 if(model){
			 model.isSilhouette(data.value);
		 }
	});
	
	form.on('select(distanceDisplayCondition)', function(data) {
		 if('0'==data.value){
			 $("#SceneVModel-distanceNear-tr").css("display",'none');
			 $("#SceneVModel-distanceFar-tr").css("display",'none');
		 }else{
			 $("#SceneVModel-distanceNear-tr").css("display",'');
			 $("#SceneVModel-distanceFar-tr").css("display",'');
		 }
		 if(model){
			 model.isDistanceDisplay(data.value);
		 }
	 });

	 form.on('radio(shadows)', function(data){
		 if(model){
			 model.isShadows(data.value);
		 };
     });

	 form.on('radio(animation)', function(data){
		 if(model){
			 model.isAnimation(data.value);
		 };
     });
	 
	form.on('submit(submitModelEditForm)', function(data) {
		layer.load(2);
		var formData = {};
		for (var key in data.field) {
			formData['SceneVModel.' + key] = data.field[key];
		}
		if(!data.field['layerId']){
			formData['SceneVModel.layerId'] = _this.editor.scene.id;
		}
		if(!data.field['sceneId']){
			formData['SceneVModel.sceneId'] = _this.editor.scene.id;
		}
		var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/model/save", formData, "json", null);
		layer.closeAll('loading');
		if (res && 200 == res.code) {
			layer.msg(res.message, {icon: 1});
			_this.editor.sceneLayer.refreshNode();
		} else {
			layer.msg(res.message, {icon: 2});
		}
		return false;
	});
}

SceneVModel.prototype.close = function(){
	var _this = this;
	if(_this.dIndex){
		layer.close(_this.dIndex);	
	}
}

/**
 * 添加模型
 */
SceneVModel.prototype.add = function(modelId){
	let _this=this;
	_this.close();
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/model/getById", {id:modelId},"json", null);
	if(200==res.code){
		let option={
			attribute:{
				modelId:res.data.id,
				name:res.data.name,
			},
			model:{
				url: _this.ctx +res.data.url,
				type: res.data.type,
				modelId: res.data.id,
			}
		};
		
		let drawModel=_this.globe.drawModel(option);
		drawModel.on('success',function(e){
			_this.globe.put(e.id,e);
			var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/model/save", {
				'SceneVModel.id': e.id ,
				'SceneVModel.name': e.name||'未命名', 
				'SceneVModel.modelId': e.model.modelId, 
				'SceneVModel.type': e.model.type,
				'SceneVModel.layerId':_this.editor.scene.id,
				'SceneVModel.sceneId':_this.editor.scene.id,
				'SceneVModel.x':e.position.x,
				'SceneVModel.y':e.position.y,
				'SceneVModel.z':e.position.z,
				'SceneVModel.sort':0,
			}, "json", null);
			if(res && 200==res.code){
				_this.editor.sceneLayer.initTree('model');
			}
			_this.open(e);
		});
	}
}

SceneVModel.prototype.createEditPModel = function(model){
	let _this=this;
	if(_this.isOpenEdit){
		if(_this.editPModel){
			_this.editPModel.destroy();
			_this.editPModel=null;
		}
		_this.editPModel=_this.globe.createEditPModel(model);
		_this.editPModel.on('change',function(e){
			if(e.heading && $("#SceneVModelHeading")) {
				$("#SceneVModelHeading").val(e.heading);
			}
			
			if(e.position && $("#modelX") && $("#modelY") && $("#modelZ")){
				$("#modelX").val(e.position.x);
				$("#modelY").val(e.position.y);
				$("#modelZ").val(e.position.z);
			}
			if(e.scale && $("#SceneVModelScale") ){
				$("#SceneVModelScale").val(e.scale);
			}
		})
	}
}

SceneVModel.prototype.closeEditPModel = function(){
	let _this=this;
	if(_this.editPModel){
		_this.editPModel.destroy();
		_this.editPModel=null;
	}
}

SceneVModel.prototype.delete = function(obj){
	let _this=this;
	if(!obj){
		layer.alert('删除失败，刷新重试！');
		return;
	}
	layer.load(2);
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/model/delete", {id:obj.id},"json", null);
	layer.closeAll('loading');
	if (res && 200==res.code) {
        layer.msg(res.message, {icon: 1});
		layer.close(_this.dIndex);
		_this.closeEditPModel();
		_this.globe.remove(obj.id);
        return true;
    } else {
        layer.msg(res.message, {icon: 2});
        return false;
    }
}
SceneVModel.prototype.renderProperty = function(){
	var _this = this;
	_this.insTb=table.render({
	    elem: '#tableModelProperty',
	    url: _this.ctx +'/property/listData',
	    page: false,
	    where:{
	    	thingId:_this.thingId
	    },
	    cols: [[
	        {field: 'label', sort: false, title: '标签', edit: 'text'},
	        {field: 'value', sort: false, title: '值', edit: 'text'},
	        {align: 'center', toolbar: '#tableModelPropertyScript', title: '操作',width:120}
	    ]]
	});
	
    // 添加
    $('#addModelPropertyBtn').click(function () {
        showEditModel();
    });

    // 工具条点击事件
    table.on('tool(tableModelProperty)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showEditModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(obj);
        }
        
    });

    // 删除
    function doDel(obj) {
        layer.confirm('确定要删除“' + obj.data.label + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
    		var res = common_ajax.ajaxFunc('post', _this.ctx + "/property/delete", {id:obj.data.id}, "json", null);
            layer.closeAll('loading');
            if (res.code == 200) {
                layer.msg(res.message, {icon: 1});
                obj.del();
                let model=_this.globe.getById(_this.thingId);
                if(model){
                	model.removeProperty(obj.data.id);
                }
            } else {
                layer.msg(res.message, {icon: 2});
            }
        });
    }

    // 显示编辑弹窗
    function showEditModel(nData) {
        layer.open({
            type: 1,
            title: (nData ? '修改' : '添加'),
            content: $('#modelModelPropertyScript').html(),
            success: function (layero, dIndex) {
                form.val('modelModelPropertyForm', nData);  // 回显数据
                form.on('submit(modelSubmitModelPropertyForm)', function (data) {
                    layer.load(2);
                    var formData={}; 
                    for(var key in data.field){
                    	formData['property.'+key]=data.field[key];
                    }
                    formData['property.thingId']=_this.thingId; 
                    formData['property.sceneId']=_this.editor.scene.id; 
                    
            		var res = common_ajax.ajaxFunc('post', _this.ctx + "/property/save", formData, "json", null);
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.close(dIndex);
                        layer.msg(res.message, {icon: 1});
                        _this.insTb.reload({where:{
                	    	thingId:_this.thingId
                	    }}, 'data');
                        let model=_this.globe.getById(_this.thingId);
                        if(model){
                        	model.updateProperty(res.data);
                        }
                    } else {
                        layer.msg(res.message, {icon: 2});
                    }
                    return false;
                });
            }
        });
    }
}

SceneVModel.prototype.renderAntenna = function(){
	var _this = this;
	_this.antennaTb=table.render({
	    elem: '#tableModelAntenna',
	    url: _this.ctx +'/antenna/listData',
	    page: false,
	    where:{
	    	thingId:_this.thingId
	    },
	    cols: [[
	        {field: 'name', sort: false, title: '标签', edit: 'text'},
	        {align: 'center', toolbar: '#tableModelAntennaScript', title: '操作',width:120}
	    ]]
	});
	
    // 添加
    $('#addModelAntennaBtn').click(function () {
        showEditModel();
    });

    // 工具条点击事件
    table.on('tool(tableModelAntenna)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showEditModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(obj);
        }
        
    });

    // 删除
    function doDel(obj) {
        layer.confirm('确定要删除“' + obj.data.name + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
    		var res = common_ajax.ajaxFunc('post', _this.ctx + "/antenna/delete", {id:obj.data.id}, "json", null);
            layer.closeAll('loading');
            if (res.code == 200) {
                layer.msg(res.message, {icon: 1});
                obj.del();
                let model=_this.globe.getById(_this.thingId);
                if(model){
                	model.removeAntenna(obj.data.id);
                }
            } else {
                layer.msg(res.message, {icon: 2});
            }
        });
    }

    // 显示编辑弹窗
    function showEditModel(nData) {
        layer.open({
            type: 1,
            title: (nData ? '修改' : '添加'),
            content: $('#modelModelAntennaScript').html(),
    	    shade:0,
    	    area: '250px',
    	    offset: ['45px', '320px'],	
    	    fixed:true,
    	    move:false,
    		skin:'layui-layer  layui-layer-adminRight layui-layer-city',
            success: function (layero, dIndex) {
            form.val('modelModelAntennaForm', nData);  // 回显数据
             
             let model=_this.globe.getById(_this.thingId);
             
           	 $('#antenna-relative-far').on('input', function() {
        		 if(model){
        			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-relative-heading').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-relative-pitch').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-relative-roll').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 
        	 
        	 $('#antenna-headin').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-pitch').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-roll').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-relative-height').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 });
        	 $('#antenna-name').on('input', function() {
        		 if(model){
         			let param= form.val('modelModelAntennaForm'); 
        			model.addAntenna(param);
        		 }
        	 }); 
        	 
        	 
    		form.on('select(antenna-position)', function(data) {
	       		 if(model){
	      			let param= form.val('modelModelAntennaForm'); 
	     			model.addAntenna(param);
	     		 }
    		});
        	 
                
	            form.on('submit(modelSubmitModelAntennaForm)', function (data) {
	                layer.load(2);
	                var formData={}; 
	                for(var key in data.field){
	                	formData['antenna.'+key]=data.field[key];
	                }
	                formData['antenna.thingId']=_this.thingId; 
	                formData['antenna.sceneId']=_this.editor.scene.id; 
	                
	        		var res = common_ajax.ajaxFunc('post', _this.ctx + "/antenna/save", formData, "json", null);
	                layer.closeAll('loading');
	                if (res.code == 200) {
	                    layer.close(dIndex);
	                    layer.msg(res.message, {icon: 1});
	                    _this.antennaTb.reload({where:{
	            	    	thingId:_this.thingId
	            	    }}, 'data');
	                    if(model){
	                    	model.addAntenna(res.data);
	                    }
	                } else {
	                    layer.msg(res.message, {icon: 2});
	                }
	                return false;
	            });
            }
        });
    }
}